/**
 * 
 */
package com.shamrock.cms.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import com.shamrock.cms.dao.AuthoritiesDao;
import com.shamrock.cms.entity.Authorities;

/**
 * @author GunnyZeng 2016年12月30日
 * MyFilterInvocationSecurityMetadataSource.java
 */
@Service("myFilterInvocationSecurityMetadataSource")
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource{

	private Logger logger  =  Logger.getLogger(getClass());
	@Autowired
	private AuthoritiesDao authoritiesDao;
	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}
	
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String url = ((FilterInvocation) object).getRequestUrl();
		logger.info(url);
		url = url.split("\\?")[0];
		List<Authorities> authorities =  authoritiesDao.getAuthoritiesByResource(url);
		List<ConfigAttribute> configAttributes = new ArrayList<>();
		for(Authorities au : authorities){
			String roles[] = au.getRole().split(",");
			for(String role: roles){
				ConfigAttribute ca = new SecurityConfig(role);
				configAttributes.add(ca);
			}
			
		}
		return configAttributes;
	}
	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}
	
}
